package com.shigu.admin.manager.services;

import com.alibaba.fastjson.JSON;
import com.opentae.data.mall.beans.ManagerPermission;
import com.opentae.data.mall.examples.ManagerPermissionExample;
import com.opentae.data.mall.interfaces.ManagerPermissionMapper;
import com.shigu.admin.manager.common.CustomPager;
import com.shigu.admin.manager.utils.PageUtil;
import com.shigu.admin.manager.vo.TreeVO;
import com.shigu.admin.manager.vo.ZTreeVO;
import com.shigu.component.shiro.AuthorityUser;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;

/**
 * 权限相关服务
 * Created by Licca on 16/5/13.
 */
@Service
public class AdminPermissionService {

    @Resource(name = "tae_mall_managerPermissionMapper")
    ManagerPermissionMapper managerPermissionMapper;

    /**
     * 使用Ztree的数据
     * @param parentId
     * @return
     */
    @RequiresPermissions(value = {"permission:sub","role:modify"},logical = Logical.OR)
    public List<ZTreeVO> selAllPermissionFortreeByParentId(Long parentId){
        List<ZTreeVO> results=new ArrayList<ZTreeVO>();
        ManagerPermissionExample example=new ManagerPermissionExample();
        ManagerPermissionExample.Criteria cri=example.createCriteria();
        cri.andStatusEqualTo(1);
        if(parentId==null){
            cri.andParentPidIsNull();
        }else{
            cri.andParentPidEqualTo(parentId);
        }
        List<ManagerPermission> list=managerPermissionMapper.selectByExample(example);
        if(parentId==null){
            List<Long> ids=new ArrayList<Long>();
            for(ManagerPermission mp:list){
                ids.add(mp.getPermissionId());
                ZTreeVO ztv=new ZTreeVO();
                ztv.setId(mp.getPermissionId());
                ztv.setName(mp.getPermissionComment() + " (" + mp.getPermissionTag() + ")");
                ztv.setpId(0l);
                ztv.setOpen(true);
                ztv.setIsParent(true);
                ztv.setChecked(false);
                ztv.setTag(mp.getPermissionTag());
                ztv.setTagComment(mp.getPermissionComment());
                results.add(ztv);
            }
            example.clear();
            example.createCriteria().andStatusEqualTo(1).andParentPidIn(ids);
            list=managerPermissionMapper.selectByExample(example);
        }
        for(ManagerPermission mp:list){
            ZTreeVO ztv=new ZTreeVO();
            ztv.setId(mp.getPermissionId());
            ztv.setName(mp.getPermissionComment() + " (" + mp.getPermissionTag() + ")");
            ztv.setpId(mp.getParentPid());
            ztv.setOpen(false);
            ztv.setChecked(false);
            ztv.setIsParent(true);
            ztv.setTag(mp.getPermissionTag());
            ztv.setTagComment(mp.getPermissionComment());
            results.add(ztv);
        }
        return results;
    }

    /**
     * 查出所有权限数据给tree
     * @return
     */
    @RequiresPermissions(value = {"permission:sub","role:modify"},logical = Logical.OR)
    public String selAllPermissionFortree(){
        ManagerPermissionExample example=new ManagerPermissionExample();
        example.setOrderByClause("parent_pid asc");
        example.createCriteria().andStatusEqualTo(1);
        List<ManagerPermission> mplist=managerPermissionMapper.selectByExample(example);
        List<TreeVO> nodes=new ArrayList<TreeVO>();
        Map<Long,TreeVO> othernodes=new HashMap<Long, TreeVO>();
        for(ManagerPermission mp:mplist){
            TreeVO tv=othernodes.get(mp.getPermissionId());
            if(tv==null){
                tv=new TreeVO();
                String text="<input type='hidden' class='hid_inp' value='"+mp.getPermissionId()+"'><font style='color: blue;'>"+mp.getPermissionTag()+"</font>."+mp.getPermissionComment();
                if(mp.getStatus()==0){
                    text+="(<font style='color: crimson;'>弃用</font>)";
                }
                tv.setText(text);
                tv.setPid(mp.getPermissionId());
//                tv.setHref("javascript:selTreeNode(" + mp.getPermissionId() + ")");
                tv.setTag(mp.getPermissionTag());
                tv.setTagComment(mp.getPermissionComment());
                if(mp.getParentPid()==null){
                    nodes.add(tv);
                }
                othernodes.put(mp.getPermissionId(),tv);
            }
            if(mp.getParentPid()!=null){
                TreeVO parentTv=othernodes.get(mp.getParentPid());
                if (parentTv!=null){
                    List<TreeVO> subnode=parentTv.getNodes();
                    if(subnode==null){
                        subnode=new ArrayList<TreeVO>();
                        parentTv.setNodes(subnode);
                    }
                    subnode.add(tv);
                }
            }
        }
        String result= JSON.toJSONString(nodes);
        result=result.replace(",\"nodes\":[]","");
        return result;
    }
    /**
     * 检测标签是否被使用过
     * @param tag
     * @return
     */
    @RequiresPermissions("permission:top")
    public ManagerPermission checkTag(String tag){
        ManagerPermissionExample example=new ManagerPermissionExample();
        example.createCriteria().andPermissionTagEqualTo(tag);
        List<ManagerPermission> list=managerPermissionMapper.selectByExample(example);
        if(list.size()>0){
            return list.get(0);
        }
        return null;
    }

    /**
     * 添加权限标签
     * @return
     */
    @RequiresPermissions(value = {"permission:sub","permission:top"},logical = Logical.OR)
    public Long addPermissionCheckTag(String tag,String tagComment,Long parentId){
        ManagerPermission mp=new ManagerPermission();
        mp.setCreateTime(new Date());
        mp.setStatus(1);
        mp.setPermissionComment(tagComment);
        if(tag.contains(":")){
            mp.setNamespace(tag.split(":")[0]);
        }
        if(parentId!=null){
            mp.setParentPid(parentId);
        }
        mp.setPermissionTag(tag);
        Subject currentUser = SecurityUtils.getSubject();
        AuthorityUser auth = (AuthorityUser) currentUser.getPrincipal();
        mp.setCreateUserId(auth.getUserId());
        managerPermissionMapper.insertSelective(mp);
        return mp.getPermissionId();
    }

    /**
     * 修改权限
     * @param tag
     * @param tagComment
     * @param pid
     * @return
     */
    @RequiresPermissions("permission:sub")
    public Integer modifyPermission(String tag,String tagComment,Long pid){
        ManagerPermission mp=new ManagerPermission();
        mp.setPermissionId(pid);
        mp.setPermissionTag(tag);
        mp.setPermissionComment(tagComment);
        return managerPermissionMapper.updateByPrimaryKeySelective(mp);
    }
    /**
     * 查询列表
     * @param keyword
     * @param pageNo
     * @param pageSize
     * @return
     */
    @RequiresPermissions("permission:list")
    public CustomPager<ManagerPermission> selList(String keyword, Integer pageNo, Integer pageSize){
        ManagerPermissionExample example=new ManagerPermissionExample();
        example.setStartIndex((pageNo - 1) * pageSize);
        example.setEndIndex(pageSize);
        example.setOrderByClause("permission_id desc");
        if(keyword!=null&&!"".equals(keyword)){
            example.createCriteria().andPermissionTagLike("%" + keyword + "%");
            example.or().andPermissionCommentLike("%"+keyword+"%");
        }
        List<ManagerPermission> list=managerPermissionMapper.selectByConditionList(example);
        int total=managerPermissionMapper.countByExample(example);
        CustomPager<ManagerPermission> pager=new CustomPager<ManagerPermission>();
        pager.setContent(list);
        pager.setNumber(pageNo - 1);
        pager.setTotalPages(PageUtil.calPage(pageSize, total));
        return pager;
    }

//    /**
//     * 单纯查列表
//     * @param keyword
//     * @param pageNo
//     * @param pageSize
//     * @return
//     */
//    public List<ManagerPermission> listBykey(String keyword,Integer pageNo,Integer pageSize){
//        ManagerPermissionExample example=new ManagerPermissionExample();
//        example.setStartIndex((pageNo - 1) * pageSize);
//        example.setEndIndex(pageSize);
//        if(keyword!=null&&!"".equals(keyword)){
//            example.createCriteria().andPermissionTagLike("%" + keyword + "%");
//            example.or().andPermissionIdLike("%"+keyword+"%");
//        }
//        List<ManagerPermission> list=managerPermissionMapper.selectByConditionList(example);
//        return list;
//    }

    /**
     * 修改状态
     * @param pid
     * @return
     */
    @RequiresPermissions("permission:sub")
    public int changeStatus(Long pid){
        ManagerPermission mp=managerPermissionMapper.selectByPrimaryKey(pid);
        if(mp==null){
            return 0;
        }
        mp.setStatus((mp.getStatus()+1)%2);
        managerPermissionMapper.updateByPrimaryKeySelective(mp);
        return 1;
    }
}
